package com.example;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class DistributeServer {

    private static final int sessionTimeout = 2000;
    private static final String connectString = "Cent7:2181,Cent7-c1:2181,Cent7-c2:2181";
    private ZooKeeper zkServer = null;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        // 获取信息
        Scanner scanner = new Scanner(System.in);
        System.out.print("输入服务名字:");
        String hostname = scanner.nextLine();
        System.out.print("输入数据:");
        String data = scanner.nextLine();

        // 1.获取zookeeper连接
        DistributeServer server = new DistributeServer();
        server.getConnection();

        // 2.注册服务器到zk集群
        server.register(hostname, data);

        // 3.启动业务逻辑
        server.business();
    }

    private void business() throws InterruptedException {

        System.out.println("业务处理完成！");

    }

    private void register(String hostname, String data) throws InterruptedException, KeeperException {
        // 形参：1.节点名以及位置 2.节点携带的数据 3.节点的权限（任何人可访问） 4.节点的类型（持久型）
        zkServer.create("/servers/" + hostname, data.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(hostname + " 已上线");
    }

    private void getConnection() throws IOException {

        zkServer = new ZooKeeper(connectString, sessionTimeout, watchedEvent -> {
        });
    }

}
